﻿using System;
using System.Collections.Generic;

using E.BLL;
using E.Model;
using E.Web.UI.Page;
using E.Enum;

using X.Common;

namespace E.Web.Teacher.exam
{
    public partial class ExamEdit : TeacherBasePage
    {
        public string act;
        public int id;
        public int cid;
        public ExamInfoModel model = new ExamInfoModel();
        public IList<DictAreaModel> areaList;
        public string area_v;
        public IDictionary<int, string> categoryList = EnumClass.GetExamCategoryList();
        public Dictionary<int, string> certificateList;

        public IList<ExamDefaultModel> defaultList;

        public int rid;

        public string targetArr;
        public string valueArr;
        public string valueArr_re;
        public string questionIDArr;

        protected override void ShowPage()
        {
            id = XRequest.GetInt("id", -1);
            cid = XRequest.GetInt("cid", -1);
            act = XRequest.GetString("act");
            if (authority == E.Enum.EnumTeacherAuthority.Internals)
            {
                certificateList = (new TeacherBLL()).GetTeacherProjectInfo(teacherid);
            }
            else
            {
                certificateList = (new CourseBLL()).GetAllCertificateAndProjectList();
            }
            //act = "n";
            EnumExamCategory categoryid = (EnumExamCategory)cid;

            ExamBLL bll = new ExamBLL();
            defaultList = bll.GetExamDefaultList();

            if (ispost)
            {
                if (CheckValue())
                {

                    string area = XRequest.GetString("area_v");
                    string[] areas = GetArray(area);

                    string title = XRequest.GetString("TitleTxt");
                    int examTime = XRequest.GetInt("ExamTimeTxt", 0);
                    DateTime startTime = Convert.ToDateTime(XRequest.GetString("StartTimeTxt"));
                    DateTime endTime = Convert.ToDateTime(XRequest.GetString("EndTimeTxt"));
                    //int relationid = XRequest.GetInt("RelationSlt", -1);
                    int category = XRequest.GetInt("ExamCategorySlt", -1);
                    int totalScore = XRequest.GetInt("TotalScoreTxt", 0);
                    int passScore = XRequest.GetInt("PassScoreTxt", 0);

                    int courseid = XRequest.GetInt("CourseSlt", -1);
                    int certificateid = XRequest.GetInt("CertificateSlt", -1);
                    string questionIDs = XRequest.GetString("valueQuestionArr");
                    int isRandom = XRequest.GetInt("rQuestionStyle", 1);

                    ExamInfoModel model = new ExamInfoModel();
                    model.CategoryID = (EnumExamCategory)category;

                    switch (model.CategoryID)
                    {
                        case EnumExamCategory.CourseExam:
                            model.CourseCertificateID = courseid;
                            model.CertificateID = certificateid;
                            break;
                        case EnumExamCategory.CertificateExam:
                            model.CourseCertificateID = certificateid;
                            break;
                        default: break;
                    }

                    model.Title = title;
                    model.StartTime = startTime;
                    model.EndTime = endTime;
                    model.ExamTime = examTime;
                    model.AreaStrList = areas;
                    model.TotalScore = totalScore;
                    model.PassScore = passScore;
                    model.QuestionIDArray = questionIDs;
                    model.IsRandom = isRandom;

                    int rst = 0;
                    string href = "";
                    if (isRandom == 1)
                    {
                        IList<SettingModelForDataHandle> settingList = GetSetting();

                        if (settingList.Count == 0)
                        {
                            Alert("试卷设置错误");
                        }
                        else
                        {

                            model.DataSettingList = settingList;

                            switch (act)
                            {
                                case "n":
                                    rst = bll.AddExam(model);

                                    //href = "/internals/exam/Edit.aspx?act=n";
                                    href = "/exam/ExamEdit.aspx?act=n";
                                    break;
                                case "u":
                                    model.ID = id;
                                    rst = bll.UpdateExam(model);
                                    //href = "/internals/exam/Edit.aspx?act=u&id=" + id + "&cid=" + category;
                                    href = "/exam/ExamEdit.aspx?act=u&id=" + id + "&cid=" + category;
                                    break;
                                default: break;
                            }


                        }
                    }
                    else
                    {
                        switch (act)
                        {
                            case "n":
                                rst = bll.AddExam(model);

                                href = "/exam/ExamEdit.aspx?act=n";
                                break;
                            case "u":
                                model.ID = id;
                                rst = bll.UpdateExam(model);
                                href = "/exam/ExamEdit.aspx?act=u&id=" + id + "&cid=" + category;
                                break;
                            default: break;
                        }
                    }
                    if (rst > 0)
                    {
                        Alert("操作成功");
                    }
                    else
                    {
                        Alert("操作失败");
                    }
                    ExecuteJS("window.location = '" + href + "';");

                }
                else
                {
                    ExecuteJS("history.back();");
                }
            }
            else
            {
                if (id != -1)
                {
                    model = bll.GetExamInfo(id, categoryid);
                    rid = model.CourseCertificateID;
                    area_v = Convert2String(model.AreaList);
                    questionIDArr = model.QuestionIDArray;
                    if (model.IsRandom == 1)
                    {
                        SetSetting(categoryid, bll.GetExamQuestionSetting(id));
                    }
                }

                areaList = GetTeacherAreaList(teacherid);
            }
        }
        private void SetSetting(EnumExamCategory categoryid, IList<ExamSettingModel> settingList)
        {
            switch (categoryid)
            { 
                case EnumExamCategory.CourseExam:
                    targetArr = "";
                    valueArr = "";
                    valueArr_re = "";
                    int i = 0;
                    foreach (ExamSettingModel esm in settingList)
                    {
                        targetArr += esm.QuestionCategoryID;
                        valueArr += esm.SettingList[0].QuestionQuantity;
                        valueArr_re += esm.SettingList[0].RequiredQuestionQuantity;
                        if (i < settingList.Count - 1)
                        {
                            targetArr += ",";
                            valueArr += ",";
                            valueArr_re += ",";
                        }
                        i++;
                    }
                    break;
                case EnumExamCategory.CertificateExam:
                    System.Text.StringBuilder targetArrSb = new System.Text.StringBuilder();
                    System.Text.StringBuilder valueArrSb = new System.Text.StringBuilder();
                    System.Text.StringBuilder valueArrSb_re = new System.Text.StringBuilder();
                    foreach (ExamSettingModel esm in settingList)
                    {
                        foreach (ExamDetailSettingModel edsm in esm.SettingList)
                        {
                            targetArrSb.Append(esm.QuestionCategoryID + "_" + edsm.CourseID);
                            valueArrSb.Append(edsm.QuestionQuantity);
                            valueArrSb_re.Append(edsm.RequiredQuestionQuantity);
                            targetArrSb.Append(",");
                            valueArrSb.Append(",");
                            valueArrSb_re.Append(",");
                        }
                    }
                    targetArr = targetArrSb.Remove(targetArrSb.Length - 1, 1).ToString();
                    valueArr = valueArrSb.Remove(valueArrSb.Length - 1, 1).ToString();
                    valueArr_re = valueArrSb_re.Remove(valueArrSb_re.Length - 1, 1).ToString();
                    break;
                default: break;
            }
        }

        private bool CheckValue()
        {
            bool rst = true;

            if (XRequest.GetString("TitleTxt").Equals(""))
            {
                Alert("试卷名称不能为空");
                rst = false;
            }

            if (XRequest.GetInt("ExamTimeTxt", 0) <= 0)
            {
                Alert("考试时间错误");
                rst = false;
            }

            if (XRequest.GetInt("TotalScoreTxt", 0) <= 0)
            {
                Alert("考试总分错误");
                rst = false;
            }

            if (XRequest.GetInt("PassScoreTxt", 0) <= 0)
            {
                Alert("通过分数错误");
                rst = false;
            }

            if (XRequest.GetString("StartTimeTxt").Equals(""))
            {
                Alert("开始时间不能为空");
                rst = false;
            }

            if (XRequest.GetString("EndTimeTxt").Equals(""))
            {
                Alert("结束时间不能为空");
                rst = false;
            }

            switch (XRequest.GetInt("ExamCategorySlt", -1))
            {
                case -1:
                    Alert("请选择试卷类型");
                    rst = false;
                    break;
                case 1:
                    if (XRequest.GetInt("CertificateSlt", -1) == -1 || XRequest.GetInt("CourseSlt", -1) == -1)
                    {
                        Alert("请选择课程及认证");
                        rst = false;
                    }
                    break;
                case 2:
                    if (XRequest.GetInt("CertificateSlt", -1) == -1)
                    {
                        Alert("请选择认证类别");
                        rst = false;
                    }
                    break;
                default:
                    Alert("试卷类型选择错误");
                    rst = false;
                    break;

            }

            if (XRequest.GetString("area_v").Equals(""))
            {
                Alert("请选择至少一个地区");
                rst = false;
            }

            try
            {
                DateTime start = Convert.ToDateTime(XRequest.GetString("StartTimeTxt"));
                DateTime end = Convert.ToDateTime(XRequest.GetString("EndTimeTxt"));

                if (start > end)
                {
                    Alert("开始时间不能大于结束时间");
                    rst = false;
                }
            }
            catch (Exception ex)
            {
                Alert("时间格式错误");
                rst = false;
            }
            return rst;
        }

        private IList<SettingModelForDataHandle> GetSetting()
        {
            string category = XRequest.GetString("categoryvalue");
            string course = XRequest.GetString("coursevalue");
            string input = XRequest.GetString("inputvalue");
            string input_re = XRequest.GetString("inputvalue_re");

            IList<SettingModelForDataHandle> dataSettingList = new List<SettingModelForDataHandle>();

            if (!category.Equals("") && !course.Equals("") && !input.Equals("") && !input_re.Equals(""))
            {
                string[] categoryArr;
                if (category.IndexOf(",") != -1)
                {
                    categoryArr = category.Split(',');
                }
                else
                {
                    categoryArr = new string[] { category };
                }
                string[] courseArr;
                if (course.IndexOf(",") != -1)
                {
                    courseArr = course.Split(',');
                }
                else
                {
                    courseArr = new string[] { course };
                }

                //普通
                IList<string[]> inputList = new List<string[]>();
                if (input.IndexOf("|") != -1)
                {
                    string[] tmpArr = input.Split('|');
                    foreach (string s in tmpArr)
                    {
                        inputList.Add(s.Split(','));
                    }
                }
                else
                {
                    inputList.Add(input.Split(','));
                }

                //必选
                IList<string[]> inputList_re = new List<string[]>();
                if (input_re.IndexOf("|") != -1)
                {
                    string[] tmpArr = input.Split('|');
                    foreach (string s in tmpArr)
                    {
                        inputList_re.Add(s.Split(','));
                    }
                }
                else
                {
                    inputList_re.Add(input_re.Split(','));
                }

                try
                {
                    if (courseArr.Length == 1)
                    {
                        int i = 0;
                        foreach (string s in categoryArr)
                        {
                            //foreach (string[] sa in inputList)
                            //{
                            //    SettingModelForDataHandle smfdh = new SettingModelForDataHandle();
                            //    smfdh.CourseID = Convert.ToInt32(courseArr[0]);
                            //    smfdh.QuestionCategoryID = Convert.ToInt32(categoryArr[i]);
                            //    smfdh.QuestionQuantity = Convert.ToInt32(sa[i]);
                            //    dataSettingList.Add(smfdh);
                            //}
                            for (int j = 0; j < inputList.Count; j++)
                            {
                                SettingModelForDataHandle smfdh = new SettingModelForDataHandle();
                                smfdh.CourseID = Convert.ToInt32(courseArr[0]);
                                smfdh.QuestionCategoryID = Convert.ToInt32(categoryArr[i]);
                                smfdh.QuestionQuantity = Convert.ToInt32(inputList[0][i]);
                                smfdh.RequiredQuestionQuantity = Convert.ToInt32(inputList_re[0][i]);
                                dataSettingList.Add(smfdh);
                            }
                            i++;

                        }
                    }
                    else
                    {
                        int i = 0;
                        foreach (string categoryid in categoryArr)
                        {
                            int j = 0;
                            foreach (string courseid in courseArr)
                            {
                                SettingModelForDataHandle smfdh = new SettingModelForDataHandle();
                                smfdh.QuestionCategoryID = Convert.ToInt32(categoryid);
                                smfdh.CourseID = Convert.ToInt32(courseid);
                                int quantity = Convert.ToInt32(inputList[i][j]);
                                int quantity_re = Convert.ToInt32(inputList_re[i][j]);
                                smfdh.QuestionQuantity = quantity;
                                smfdh.RequiredQuestionQuantity = quantity_re;
                                dataSettingList.Add(smfdh);
                                j++;
                            }
                            i++;
                        }
                    }
                }
                catch (Exception e)
                { }

            }
            return dataSettingList;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}
